<template>
  <div v-if="visible" class="floating-panel">
    <span class="close-btn" role="button" aria-label="关闭" tabindex="0" @click="handleCancel" @keydown.enter="handleCancel">×</span>
    <div class="floating-panel__header">网格</div>
    <div class="floating-panel__body">
      <el-form ref="formRef" :model="form" label-width="60px" size="small" class="section-form">
        <div class="form-row">
          <span>网格尺寸:</span>
          <!-- bind to form.meshSize (number) -->
          <el-slider v-model.number="form.meshSize" :min="0.5" :max="10" :step="0.5" show-input />
        </div>

        <div class="form-actions">
          <el-button size="small" @click="meshEvent" :disabled="!form.meshSize">网格剖分</el-button>
          <el-button type="primary" size="small" @click="handleConfirm" :disabled="!form.meshSize">确认</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import type { ProjectTreeNode } from '@/store/modules/tree'
import { usePropertyForm } from '../composables/usePropertyForm'
import eventBus from '@/utils/eventBus'
import {meshCreate} from "@/api/PyFem";
import {ElMessage} from "element-plus";
import {getMeshJson} from "@/api/system/JavaFem";

const props = defineProps<{
  node?: ProjectTreeNode | null
  projectId?: number | string | null
  geoFileUrl?: string | null
}>()

const emit = defineEmits<{ (e: 'confirm'): void; (e: 'cancel'): void }>()

// form keeps properties to be saved; include meshSize as number so saving persists it
const form = reactive<{
  meshSize: number,
  meshJson?:string
}>({
  meshSize: 5.0 ,
  meshJson: ''
})

const visible = ref(true)

function handleCancel() {
  visible.value = false
  emit('cancel')
}
function handleKey(e: KeyboardEvent) {
  if (e.key === 'Escape' && visible.value) handleCancel()
}

onMounted(async () => {
  window.addEventListener('keydown', handleKey);
  if (!form.meshJson) return;
  try {
    const getMeshJsonParams = { filePath: form.meshJson };
    console.log('getMeshJsonParams:', getMeshJsonParams);
    const { data } = await getMeshJson(getMeshJsonParams);
    const emitJson = {
      data,
      mashSize: form.meshSize
    };
    eventBus.emit('existMeshEvent', emitJson);
  } catch (err) {
    console.error('getMeshJson error:', err);
  }
});
onBeforeUnmount(() => window.removeEventListener('keydown', handleKey))

const wrapperEmit = (e: 'confirm' | 'cancel') => { if (e === 'confirm') emit('confirm'); else emit('cancel') }
const { formRef, handleConfirm: rawConfirm } = usePropertyForm(form, { node: props.node, projectId: props.projectId }, wrapperEmit)

function handleConfirm() {
  // ensure meshSize is a number
  form.meshSize = Number(form.meshSize) || 0
  // rawConfirm will persist form (including meshSize)
  rawConfirm()
}

const meshEvent = async () => {
  try {
    const meshData = {
      fileName: props.geoFileUrl,
      meshSize: Number(form.meshSize) || 5
    };
    const res = await meshCreate(meshData);

    // 生成 meshJson 路径
    const mshJson = toMshJson(props.geoFileUrl ?? '');
    form.meshJson = mshJson;

    // 写入 node.property
    if (props.node) {
      props.node.property ??= {};
      props.node.property.meshJson = mshJson;
    }
    console.log('meshJson:', mshJson);
    // 发送事件
    eventBus.emit('meshEvent', res);
  } catch (err) {
    console.error('meshCreate error:', err);
    ElMessage.error((err as any)?.message || '提交计算失败');
  }
};



const toMshJson = (url:string) => url.replace(/\.[^.]+$/, '_msh.json');

</script>

<style scoped lang="scss">
@use './common.scss' as *;
.section-form { display: flex; flex-direction: column; gap: 12px; }
.form-row { display:flex; align-items:center; gap: 12px; }
.form-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }
</style>